package com.dahuyou.monitor.method;

//import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;

import java.lang.instrument.Instrumentation;

public class MyPreMain {

    public static void premain(String agentArgs, Instrumentation instrumentation) {
        System.out.println("the agent args is：" + agentArgs);
        AgentBuilder.Transformer transformer = (builder, typeDescription, classLoader, javaModule) -> {
            // 主要设置代理，以及拦截的方法（拦截的方法不太清楚为什么要在这里设置，不应该和设置要拦截的类在一起吗？）
            return builder.method(ElementMatchers.any())
                    .intercept(MethodDelegation.to(MyByteBuddyDelegator.class));
        };

        AgentBuilder.Listener listener = new AgentBuilder.Listener() {
            @Override
            public void onDiscovery(String s, ClassLoader classLoader, JavaModule javaModule, boolean b) {

            }

            @Override
            public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, boolean b, DynamicType dynamicType) {

            }

            @Override
            public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, boolean b) {

            }

            @Override
            public void onError(String s, ClassLoader classLoader, JavaModule javaModule, boolean b, Throwable throwable) {

            }

            @Override
            public void onComplete(String s, ClassLoader classLoader, JavaModule javaModule, boolean b) {

            }
        };
        new AgentBuilder
                .Default()
                .type(ElementMatchers.nameStartsWith("com.dahuyou.monitor.method")) // 指定要拦截的类包前缀
                .transform(transformer)
                .with(listener)
                .installOn(instrumentation);
    }

    /**
     * 有public static void premain(String agentArgs, Instrumentation instrumentation)这个方法，本方法不会被调用
     * @param agentArgs
     */
    public static void premain(String agentArgs) {}
}
